import { BadRequestException, Module } from '@nestjs/common';
import { FileManageService } from './file-manage.service';
import { FileManageController } from './file-manage.controller';
import { diskStorage } from 'multer';
import { extname, join } from 'path';
import { MulterModule } from '@nestjs/platform-express';

@Module({
  controllers: [FileManageController],
  providers: [FileManageService],
  imports: [
    MulterModule.register({
      storage: diskStorage({
        destination:
          process.env.STORAGE_ADDRESS ||
          join(__dirname, '../../../fileStorage'),
        filename: (req, file, callback) => {
          const fileName =
            `${Date.now()}-${Math.random()}` + extname(file.originalname);
          callback(null, fileName);
        },
      }),
      fileFilter: (req, file, callback) => {
        const allowedTypes =
          /\.(jpg|jpeg|png|mp4|avi|mov|mp3|wav|ogg|xlsx|xls|csv)$/i;
        if (allowedTypes.test(extname(file.originalname).toLowerCase())) {
          return callback(null, true);
        } else {
          callback(new BadRequestException('文件格式不正确'), false);
        }
      },
      limits: {
        fileSize: 25 * 1024 * 1024,
      },
    }),
  ],
})
export class FileManageModule {}
